package logic

import (
	"encoding/json"
	"fmt"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"go_spider_api/models"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)




// 查询所有任务列表,
func GetJobs() (jobMap *models.JobList) {
	client := &http.Client{}
	url := fmt.Sprintf("http://%s:%d/listjobs.json?project=shiji", viper.GetString("scrapyd.host"), viper.GetInt("scrapyd.port"))
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("User-Agent", "Apipost client Runtime/+https://www.apipost.cn/")
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)

	}
	bodyText, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	jobMap = new(models.JobList)
	err = json.Unmarshal(bodyText, jobMap)
	return



	//fmt.Printf("%s\n", bodyText)

}

// 调用scrapyd api,启动对应爬虫
func StartSpider(spiderName string) (err error) {
	client := &http.Client{}

	readStr := fmt.Sprintf("project=shiji&spider=%s", spiderName)
	url := fmt.Sprintf("http://%s:%d/schedule.json", viper.GetString("scrapyd.host"), viper.GetInt("scrapyd.port"))
	fmt.Println(url)

	var data = strings.NewReader(readStr)
	req, err := http.NewRequest("POST", url, data)
	if err != nil {
		zap.L().Error("访问scrapyd启动爬虫接口失败", zap.Error(err))
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	resp, err := client.Do(req)
	defer resp.Body.Close()
	if err != nil {
		zap.L().Error("访问scrapyd启动爬虫接口失败", zap.Error(err))

	}
	_, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		zap.L().Error("访问scrapyd启动爬虫接口失败", zap.Error(err))

	}
	//fmt.Printf("b: %v\n", string(bodyText))
	return
}
// 停止爬虫服务，根据linux 的指令来进行操作


//package main
//
//import (
//"fmt"
//"io/ioutil"
//"log"
//"net/http"
//"strings"
//)
//
//func main() {
//	client := &http.Client{}
//	var data = strings.NewReader(`project=shiji&spider=fangchanchaoshi_chuzu`)
//	req, err := http.NewRequest("POST", "http://192.168.0.7:9996/schedule.json", data)
//	if err != nil {
//		log.Fatal(err)
//	}
//	req.Header.Set("User-Agent", "Apipost client Runtime/+https://www.apipost.cn/")
//	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
//	resp, err := client.Do(req)
//	if err != nil {
//		log.Fatal(err)
//	}
//	bodyText, err := ioutil.ReadAll(resp.Body)
//	if err != nil {
//		log.Fatal(err)
//	}
//	fmt.Printf("%s\n", bodyText)
//}

